﻿using HuntingFishGame.H5.Models.LogCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HuntingFishGame.H5.Models.WeChatCommon
{
    public class WxPayUtil
    {/// <summary>
        /// 在线支付
        /// </summary>
        /// <param name="orderMoney">交易金额(单位：分)</param>                        
        /// <param name="openId">微信授权用户Id</param>
        /// <param name="traderOrderID">商户交易订单号</param>
        /// <param name="proName">商品或支付单简要描述</param>
        /// <param name="proDesc">商品名称明细列表</param>        
        /// <param name="attach">附加参数（用于处理支付结果验证）</param>
        /// <param name="notify_url">商户提供的商户前台系统异步支付回调地址</param>        
        public static string PayJsApiRequst(int orderMoney, string openId, string traderOrderID, string proName, string proDesc, string attach, string notify_url)
        {
            string jsApiParameters = "";

            //若传递了相关参数，则调统一下单接口，获得后续相关接口的入口参数
            JsApiPay jsApiPay = new JsApiPay(System.Web.HttpContext.Current.Request, System.Web.HttpContext.Current.Response);
            jsApiPay.openid = openId;
            jsApiPay.total_fee = orderMoney;

            //JSAPI支付预处理
            try
            {
                //统一下单
                WxPayData data = new WxPayData();
                data.SetValue("body", proName);
                data.SetValue("detail", proDesc);
                data.SetValue("attach", attach);
                data.SetValue("out_trade_no", traderOrderID);
                data.SetValue("total_fee", orderMoney);
                data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
                data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
                data.SetValue("goods_tag", "");//(选填)商品标记，代金券或立减优惠功能的参数，说明详见代金券或立减优惠
                data.SetValue("trade_type", "JSAPI");
                data.SetValue("openid", openId);
                if (!string.IsNullOrEmpty(notify_url))
                {
                    data.SetValue("notify_url", notify_url);
                }

                //XXF.Log.CommLog.Write("请求参数："+data.ToXml());                
                WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(data);
                jsApiParameters = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数   
                BSF.Log.CommLog.Write(jsApiParameters);
                BSF.Log.CommLog.Write(Newtonsoft.Json.JsonConvert.SerializeObject(unifiedOrderResult));
            }
            catch (Exception ex)
            {
                BSF.Log.ErrorLog.Write(ex.Message, ex);
            }

            return jsApiParameters;
        }
    }
}